<template>
  <div class="appointment-records">
    <!-- 头部 -->
    <div class="header-section">
      <div class="header-title">
        <el-icon class="title-icon"><List /></el-icon>
        <h1>预约记录</h1>
      </div>
      <div class="header-subtitle">
        <p>查看您的专家预约申请记录和状态</p>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-card class="filter-card">
        <div class="filter-content">
          <div class="filter-item">
            <span class="filter-label">预约类型：</span>
            <el-select
              v-model="filterParams.appointmentType"
              placeholder="全部类型"
              clearable
              style="width: 150px;"
              @change="handleFilterChange"
            >
              <el-option label="线上答疑" :value="1" />
              <el-option label="线下预约" :value="2" />
            </el-select>
          </div>
          
          <div class="filter-item">
            <span class="filter-label">预约状态：</span>
            <el-select
              v-model="filterParams.status"
              placeholder="全部状态"
              clearable
              style="width: 150px;"
              @change="handleFilterChange"
            >
              <el-option label="待确认" :value="0" />
              <el-option label="已确认" :value="1" />
              <el-option label="已完成" :value="2" />
              <el-option label="已取消" :value="3" />
            </el-select>
          </div>
          
          <div class="filter-actions">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 预约记录列表 -->
    <div class="records-section">
      <el-card class="records-card">
        <template #header>
          <div class="records-header">
            <span class="records-title">预约记录</span>
            <span class="records-count">共 {{ filteredRecords.length }} 条记录</span>
          </div>
        </template>

        <div class="records-list">
          <div
            v-for="record in paginatedRecords"
            :key="record.id"
            class="record-item"
          >
            <div class="record-header">
              <div class="expert-info">
                <el-avatar :size="50" :src="record.expertAvatar" />
                <div class="expert-details">
                  <h4 class="expert-name">{{ record.expertName }}</h4>
                  <p class="appointment-type">
                    <el-tag :type="record.appointmentType === 1 ? 'primary' : 'success'" size="small">
                      {{ record.appointmentType === 1 ? '线上答疑' : '线下预约' }}
                    </el-tag>
                  </p>
                </div>
              </div>
              <div class="record-status">
                <el-tag :type="getStatusType(record.status)" effect="light">
                  {{ getStatusText(record.status) }}
                </el-tag>
                <p class="apply-time">{{ formatTime(record.applyTime) }}</p>
              </div>
            </div>

            <div class="record-content">
              <div class="problem-preview">
                <p class="problem-text">{{ record.problemDescription }}</p>
              </div>
              
              <div class="record-details">
                <div class="detail-item" v-if="record.appointmentType === 1">
                  <el-icon><Clock /></el-icon>
                  <span class="label">预约时间：</span>
                  <span class="value">{{ record.appointmentTime ? formatTime(record.appointmentTime) : '待专家确认' }}</span>
                </div>
                
                <div class="detail-item" v-if="record.appointmentType === 2">
                  <el-icon><Location /></el-icon>
                  <span class="label">预约地点：</span>
                  <span class="value">{{ record.location || '待专家确认' }}</span>
                </div>
                
                <div class="detail-item">
                  <el-icon><Phone /></el-icon>
                  <span class="label">联系方式：</span>
                  <span class="value">{{ record.contact }}</span>
                </div>
              </div>
            </div>

            <div class="record-footer">
              <div class="record-actions">
                <el-button
                  type="primary"
                  text
                  @click="viewRecordDetail(record)"
                >
                  <el-icon><View /></el-icon>
                  查看详情
                </el-button>
                
                <el-button
                  v-if="record.status === 0"
                  type="warning"
                  text
                  @click="cancelAppointment(record)"
                >
                  <el-icon><Close /></el-icon>
                  取消预约
                </el-button>
                
                <el-button
                  v-if="record.status === 1 && record.appointmentType === 1"
                  type="success"
                  @click="startConsultation(record)"
                >
                  <el-icon><VideoCamera /></el-icon>
                  开始咨询
                </el-button>
                
                <el-button
                  v-if="record.status === 2"
                  type="info"
                  text
                  @click="viewConsultationRecord(record)"
                >
                  <el-icon><Document /></el-icon>
                  查看记录
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="filteredRecords.length === 0" class="empty-state">
          <el-empty description="暂无预约记录">
            <el-button type="primary" @click="$router.push('/farmer/expertAssistance/appointment')">
              去预约专家
            </el-button>
          </el-empty>
        </div>

        <!-- 分页 -->
        <div v-if="filteredRecords.length > 0" class="pagination-section">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="filteredRecords.length"
            layout="total, prev, pager, next, jumper"
            @current-change="handlePageChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 记录详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="预约详情"
      width="700px"
      class="detail-dialog"
    >
      <div v-if="selectedRecord" class="record-detail">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="专家姓名">
            {{ selectedRecord.expertName }}
          </el-descriptions-item>
          <el-descriptions-item label="预约类型">
            <el-tag :type="selectedRecord.appointmentType === 1 ? 'primary' : 'success'">
              {{ selectedRecord.appointmentType === 1 ? '线上答疑' : '线下预约' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预约状态">
            <el-tag :type="getStatusType(selectedRecord.status)">
              {{ getStatusText(selectedRecord.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">
            {{ formatTime(selectedRecord.applyTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="联系方式">
            {{ selectedRecord.contact }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedRecord.appointmentTime" label="预约时间">
            {{ formatTime(selectedRecord.appointmentTime) }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedRecord.location" label="预约地点">
            {{ selectedRecord.location }}
          </el-descriptions-item>
        </el-descriptions>

        <el-card class="detail-card" style="margin-top: 20px;">
          <template #header>
            <span class="detail-card-title">问题描述</span>
          </template>
          <p>{{ selectedRecord.problemDescription }}</p>
        </el-card>

        <el-card class="detail-card" style="margin-top: 20px;" v-if="selectedRecord.remarks">
          <template #header>
            <span class="detail-card-title">补充说明</span>
          </template>
          <p>{{ selectedRecord.remarks }}</p>
        </el-card>

        <div class="detail-actions" style="margin-top: 24px; text-align: center;">
          <el-button
            v-if="selectedRecord.status === 0"
            type="warning"
            @click="cancelAppointment(selectedRecord)"
          >
            取消预约
          </el-button>
          <el-button
            v-if="selectedRecord.status === 1 && selectedRecord.appointmentType === 1"
            type="success"
            @click="startConsultation(selectedRecord)"
          >
            开始咨询
          </el-button>
          <el-button @click="showDetailDialog = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  List, Search, Refresh, View, Close, VideoCamera, Document, Clock, Location, Phone
} from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const currentPage = ref(1)
const pageSize = ref(10)
const showDetailDialog = ref(false)
const selectedRecord = ref(null)

// 筛选参数
const filterParams = reactive({
  appointmentType: null,
  status: null
})

// 预约记录数据
const appointmentRecords = ref([])

// 计算属性
const filteredRecords = computed(() => {
  let filtered = appointmentRecords.value
  
  if (filterParams.appointmentType !== null) {
    filtered = filtered.filter(record => record.appointmentType === filterParams.appointmentType)
  }
  
  if (filterParams.status !== null) {
    filtered = filtered.filter(record => record.status === filterParams.status)
  }
  
  return filtered.sort((a, b) => new Date(b.applyTime) - new Date(a.applyTime))
})

const paginatedRecords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredRecords.value.slice(start, end)
})

// 方法
const formatTime = (timeString) => {
  return new Date(timeString).toLocaleString('zh-CN')
}

const getStatusText = (status) => {
  const statusMap = { 0: '待确认', 1: '已确认', 2: '已完成', 3: '已取消' }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status) => {
  const types = { 0: 'warning', 1: 'success', 2: 'info', 3: 'danger' }
  return types[status] || 'info'
}

const handleFilterChange = () => {
  currentPage.value = 1
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleReset = () => {
  Object.assign(filterParams, {
    appointmentType: null,
    status: null
  })
  currentPage.value = 1
}

const handlePageChange = (page) => {
  currentPage.value = page
}

const viewRecordDetail = (record) => {
  selectedRecord.value = record
  showDetailDialog.value = true
}

const cancelAppointment = async (record) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消此预约吗？',
      '取消预约',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '再想想',
        type: 'warning'
      }
    )
    
    // 更新预约状态
    record.status = 3
    updateLocalStorage()
    
    ElMessage.success('预约已取消')
    showDetailDialog.value = false
  } catch (error) {
    // 用户取消操作
  }
}

const startConsultation = (record) => {
  router.push('/farmer/expertAssistance/qa')
}

const viewConsultationRecord = (record) => {
  ElMessage.info('查看咨询记录功能开发中...')
}

const updateLocalStorage = () => {
  localStorage.setItem('expertAppointments', JSON.stringify(appointmentRecords.value))
}

// 示例数据
const getSampleAppointmentRecords = () => {
  return [
    {
      id: 1,
      expertName: "张教授",
      expertAvatar: "https://example.com/avatar1.jpg",
      appointmentType: 1,
      status: 1,
      applyTime: "2024-01-15T10:30:00",
      appointmentTime: "2024-01-20T14:00:00",
      contact: "13800138000",
      problemDescription: "关于果树病虫害防治的咨询，特别是苹果树的常见病害识别与处理方法。",
      location: "",
      remarks: "希望专家能提供一些实用的生物防治方法"
    },
    {
      id: 2,
      expertName: "李博士",
      expertAvatar: "https://example.com/avatar2.jpg",
      appointmentType: 2,
      status: 0,
      applyTime: "2024-01-18T09:15:00",
      appointmentTime: "",
      contact: "13900139000",
      problemDescription: "土壤改良和肥料配比问题，需要现场检测土壤样本。",
      location: "市农业技术推广中心",
      remarks: "请携带土壤检测仪"
    },
    {
      id: 3,
      expertName: "王研究员",
      expertAvatar: "https://example.com/avatar3.jpg",
      appointmentType: 1,
      status: 2,
      applyTime: "2024-01-10T11:20:00",
      appointmentTime: "2024-01-12T15:30:00",
      contact: "13700137000",
      problemDescription: "温室大棚蔬菜种植技术咨询，特别是冬季保温和光照管理。",
      location: "",
      remarks: "已提供详细咨询报告"
    },
    {
      id: 4,
      expertName: "赵专家",
      expertAvatar: "https://example.com/avatar4.jpg",
      appointmentType: 2,
      status: 3,
      applyTime: "2024-01-05T14:45:00",
      appointmentTime: "2024-01-15T10:00:00",
      contact: "13600136000",
      problemDescription: "农机设备维护保养咨询，特别是播种机的春季检修要点。",
      location: "县农机服务中心",
      remarks: "用户主动取消"
    }
  ];
};

const loadAppointmentRecords = () => {
  const storedRecords = JSON.parse(localStorage.getItem('expertAppointments') || '[]');
  appointmentRecords.value = storedRecords;
  
  // 如果本地存储没有数据，则加载示例数据
  if (storedRecords.length === 0) {
    appointmentRecords.value = getSampleAppointmentRecords();
    updateLocalStorage();
  }
};

onMounted(() => {
  loadAppointmentRecords()
})
</script>

<style scoped>
.appointment-records {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 头部样式 */
.header-section {
  text-align: center;
  margin-bottom: 24px;
  padding: 40px 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  color: white;
}

.header-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  margin-bottom: 12px;
}

.title-icon {
  font-size: 40px;
}

.header-title h1 {
  margin: 0;
  font-size: 36px;
  font-weight: 700;
}

.header-subtitle p {
  margin: 0;
  font-size: 18px;
  opacity: 0.9;
}

/* 筛选区域 */
.filter-section {
  margin-bottom: 24px;
}

.filter-card {
  border-radius: 12px;
}

.filter-content {
  display: flex;
  align-items: center;
  gap: 24px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-label {
  color: #606266;
  font-weight: 500;
  white-space: nowrap;
}

.filter-actions {
  margin-left: auto;
}

/* 记录列表 */
.records-section {
  margin-bottom: 24px;
}

.records-card {
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.records-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.records-title {
  font-size: 20px;
  font-weight: 600;
  color: #2d3748;
}

.records-count {
  color: #718096;
  font-size: 14px;
}

.records-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.record-item {
  background: white;
  border: 1px solid #f0f0f0;
  border-radius: 12px;
  padding: 24px;
  transition: all 0.3s ease;
}

.record-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.expert-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.expert-details .expert-name {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
}

.record-status {
  text-align: right;
}

.apply-time {
  margin: 8px 0 0 0;
  color: #909399;
  font-size: 14px;
}

.record-content {
  margin-bottom: 20px;
}

.problem-preview {
  margin-bottom: 16px;
}

.problem-text {
  margin: 0;
  color: #718096;
  line-height: 1.6;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.record-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.detail-item .el-icon {
  color: #667eea;
}

.label {
  color: #718096;
}

.value {
  color: #2d3748;
  font-weight: 500;
}

.record-footer {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.record-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

/* 空状态 */
.empty-state {
  padding: 60px 0;
}

/* 分页 */
.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

/* 详情对话框 */
.detail-dialog {
  border-radius: 16px;
}

.record-detail {
  padding: 8px 0;
}

.detail-card {
  border-radius: 8px;
}

.detail-card-title {
  font-weight: 600;
  color: #2d3748;
}

.detail-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .appointment-records {
    padding: 16px;
  }
  
  .header-title {
    flex-direction: column;
    gap: 8px;
  }
  
  .header-title h1 {
    font-size: 28px;
  }
  
  .filter-content {
    flex-direction: column;
    gap: 16px;
  }
  
  .filter-item {
    width: 100%;
    justify-content: space-between;
  }
  
  .filter-actions {
    width: 100%;
    justify-content: space-between;
    margin-left: 0;
  }
  
  .record-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .record-status {
    text-align: left;
  }
  
  .record-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .detail-actions {
    flex-direction: column;
    gap: 8px;
  }
}
</style>